import { ref, Ref } from "vue";
import { IFileListItem } from "@/types/file";
import { ISession } from "@/types/session.ts";
import { IGroupMemberInfo } from "@/types/group.ts";
import { IBasicMenuItem } from "@/types/common";
import { IMessage, MessageType } from "@/types/chat";
import { IFriendGroupItem, IShowFriendListModal, ShowFriendListModal } from "@/types/friend";
import { useChat } from "@/store/modules/chat.ts";
import { useUser } from "@/store/modules/user.ts";
import { useMitt } from "@/hooks/useMitt.ts";
import { useCache } from "@/store/modules/cache";
import { useSession } from "@/store/modules/session.ts";
import { IsWithin3Minutes } from "@/utils/time";
import { MessageStrategyMap } from "@/tactics/message";
import { DeleteFriendGroup } from "@/api/user";
import { ElMessage } from "element-plus";

// 会话菜单
export function useSessionMenu() {
  const session = useSession();
  const SessionListMenu: IBasicMenuItem[] = [
    {
      label: "复制账号",
      icon: "icon-fuzhi",
      click: (_event: MouseEvent, item: ISession) => {
        navigator.clipboard.writeText(item.toId?.toString()!);
        ElMessage.success("复制成功");
      },
    },
    {
      label: (item: ISession) => {
        return item.isPinned ? "取消置顶" : "置顶";
      },
      icon: (item: ISession) => {
        return item.isPinned ? "icon-cancelzhiding-copy" : "icon-zhiding";
      },
      click: async (_event: MouseEvent, item: ISession) => {
        let newPinned = item.isPinned === 0;
        await session.PinnedSession(item.sessionId, newPinned);
      },
    },
    {
      label: "标记未读",
      icon: "icon-biaojiweidu",
      click: (_event: MouseEvent, item: ISession) => {
        session.UpdateSessionByField(item.sessionId, { unread: 1 });
      },
    },
    {
      label: "从会话列表删除",
      icon: "icon-shanchu",
      click: (_event: MouseEvent, item: ISession) => {
        session.RemoveSession(item.sessionId);
      },
    },
  ];

  return {
    SessionListMenu,
  };
}

// 聊天菜单
export function useChatMenu() {
  const chat = useChat();
  const user = useUser();

  const ChatTextMenu: IBasicMenuItem[] = [
    {
      label: "复制",
      icon: "icon-fuzhi",
      click: (_e: MouseEvent, item: IMessage) => {
        navigator.clipboard.writeText(item.content);
        ElMessage.success("复制成功");
      },
    },
    {
      label: "收藏",
      icon: "icon-shoucang",
      click: () => {},
    },
    {
      label: "引用",
      icon: "icon-yinyong",
      click: (_e: MouseEvent, item: IMessage) => {
        useMitt.emit("quotation", item);
      },
    },
    {
      label: "询问NexaAI",
      icon: "icon-aislogo",
      click: () => {
        window.electronApi.createChildWindow({
          title: "quickAsk",
          path: "quickAsk",
        });
      },
    },
    {
      label: "翻译文本",
      icon: "icon-fanyi",
      click: () => {},
    },
    {
      label: "撤回",
      icon: "icon-withdraw",
      click: async (_e: MouseEvent, item: IMessage) => {
        console.log("点击了撤回消息", item);
        if (!IsWithin3Minutes(item.createdAt)) {
          ElMessage.warning("消息已过撤回最大时间限制");
          return;
        }
        const withdrawStrategy = MessageStrategyMap[MessageType.withdraw];
        const message = withdrawStrategy.mergeChatObj({ content: item.uuid });
        withdrawStrategy.sendMessage(message);
      },
    },
    {
      label: "删除",
      icon: "icon-shanchu",
      click: async (_e: MouseEvent, item: IMessage) => {
        let res = await window.electronApi.deleteMessageByOne(item.uuid, user.userId!);
        if (!res) {
          ElMessage.error("删除失败");
          return;
        }
        chat.MessageList = chat.MessageList.filter((message) => message.uuid != item.uuid);
        ElMessage.success("删除成功");
      },
    },
  ];

  const ChatImageOrFileMenu: IBasicMenuItem[] = [
    {
      label: "另存为",
      icon: "icon-lingcunwei",
      click: async (_e: MouseEvent, item: IMessage) => {
        if (!item.localPath || item.localPath === "") {
          ElMessage.error("请先下载文件");
          return;
        }
        await window.electronApi.saveFileAs(item.localPath);
      },
    },
    {
      label: "打开文件位置",
      icon: "icon-wenjianjia1",
      click: async (_e: MouseEvent, item: IMessage) => {
        if (!item.localPath || item.localPath === "") {
          ElMessage.error("请先下载文件");
          return;
        }
        let res = await window.electronApi.openFileDirectoryByPath(item.localPath);
        if (!res) ElMessage.error("打开文件失败，请检查文件路径");
      },
    },
    {
      label: "删除",
      icon: "icon-shanchu",
      click: async (_e: MouseEvent, item: IMessage) => {
        let res = await window.electronApi.deleteMessageByOne(item.uuid, user.userId!);
        if (!res) {
          ElMessage.error("删除失败");
          return;
        }
        chat.MessageList = chat.MessageList.filter((message) => message.uuid != item.uuid);
        ElMessage.success("删除成功");
      },
    },
  ];

  const ChatGroupMemberMenu: IBasicMenuItem[] = [
    {
      label: "发送消息",
      icon: "icon-xiaoxi1",
      click: () => {},
    },
    {
      label: "他/她",
      icon: "icon-aite",
      click: (_e: MouseEvent, item: IGroupMemberInfo) => {
        useMitt.emit("aitMention", item);
      },
    },
    {
      label: "查看资料",
      icon: "icon-ziliao",
      click: (_e: MouseEvent, item: IGroupMemberInfo) => {
        useMitt.emit("showPopover", item);
      },
    },
    {
      label: "修改群昵称",
      icon: "icon-xiugai",
      click: () => {},
    },
  ];

  return {
    ChatTextMenu,
    ChatImageOrFileMenu,
    ChatGroupMemberMenu,
  };
}

//文件列表菜单
export function useFileListMenu() {
  const FileListMenu: IBasicMenuItem[] = [
    {
      label: "另存为",
      icon: "icon-lingcunwei",
      click: async (_e: Event, item: IFileListItem) => {
        if (!item.localPath) {
          ElMessage.error("请先下载文件");
          return;
        }
        let ok = await window.electronApi.saveFileAs(item.localPath);
        if (!ok) ElMessage.warning("另存为失败");
      },
    },
    {
      label: "复制文件",
      icon: "icon-fuzhi",
      click: async (_event: MouseEvent, item: IFileListItem) => {
        if (!item.localPath) {
          ElMessage.error("请先下载文件");
          return;
        }
        let res = await window.electronApi.copyFileByPath(item.localPath);
        if (res) ElMessage.success("复制成功");
        else ElMessage.error("复制出现错误，请检查文件");
      },
    },
    {
      label: "打开文件",
      icon: "icon-wenjianjia",
      click: (_e: Event, item: IFileListItem) => {
        if (item.localPath === "") {
          ElMessage.error("请先下载文件");
          return;
        }
        window.electronApi.openFileByPath(item.localPath);
      },
    },
    {
      label: "打开文件位置",
      icon: "icon-wenjianjia1",
      click: async (_e: Event, item: IFileListItem) => {
        if (item.localPath === "") {
          ElMessage.error("请先下载文件");
          return;
        }
        let res = await window.electronApi.openFileDirectoryByPath(item.localPath);
        if (!res) ElMessage.error("打开文件失败，请检查文件路径");
      },
    },
  ];
  return {
    FileListMenu,
  };
}

// 好友分组菜单
export function useFriendListMenu(InputElement: Ref) {
  const cache = useCache();
  let ShowModal = ref<IShowFriendListModal>({
    friendGroupId: null,
    status: false,
    type: ShowFriendListModal.add,
  });

  const FriendListMenu: IBasicMenuItem[] = [
    {
      label: "添加分组",
      icon: "icon-plus",
      click: (_event: MouseEvent, item: IFriendGroupItem) => {
        ShowModal.value = {
          friendGroupId: item.id,
          status: true,
          type: ShowFriendListModal.add,
        };
      },
    },
    {
      label: "重命名分组",
      icon: "icon-xiugai",
      click: (_event: MouseEvent, item: IFriendGroupItem) => {
        if (item.isDefault) {
          ElMessage.warning("默认分组不允许重命名");
          return;
        }
        InputElement.value = item.name;
        ShowModal.value = {
          friendGroupId: item.id,
          status: true,
          type: ShowFriendListModal.edit,
        };
      },
    },
    {
      label: "删除分组",
      icon: "icon-shanchu",
      click: async (_event: MouseEvent, item: IFriendGroupItem) => {
        if (item.isDefault) {
          ElMessage.warning("默认分组不允许删除");
          return;
        }
        let res = await DeleteFriendGroup(item.id);
        if (res?.status != 200) {
          ElMessage.error("删除失败");
          return;
        }
        cache.DeleteFriendGroupCache(item.id, res.data);
        ElMessage.success("删除成功");
      },
    },
  ];

  function ReSetModal() {
    ShowModal.value = {
      friendGroupId: null,
      status: false,
      type: ShowFriendListModal.add,
    };
  }

  return {
    FriendListMenu,
    ReSetModal,
    ShowModal,
  };
}
